import React, { useEffect, useState } from 'react';
import { Form, Input, Select } from 'antd';
import { fetchFondsListByUnitId } from '@/api/fonds';
import { appState } from '@/store/mobx';
import { fetchATListByFondId } from '@/api/archivesType';
import { IFond } from '@/interfaces/fond';
import { IArchiveType } from '@/interfaces/archiveType';
import JPDatePicker from '@/components/JPComponents/JPDatePicker';

const { Option } = Select;

interface IAuditFormItemProps {
  visible: boolean;
}

function AuditFormItem(props: IAuditFormItemProps) {
  const { visible } = props;
  const form = Form.useFormInstance();

  const [fondList, setFondList] = useState<IFond[]>([]);
  const [aTList, setATList] = useState<IArchiveType[]>([]);
  const [selectFond, setSelectFond] = useState<number>(null);

  useEffect(() => {
    if (visible) {
      console.log('add dialog show');
      fetchFondsListByUnitId(appState.unitId).then((res) => {
        const { data } = res;
        setFondList(data);
        if (data.length > 0) {
          setSelectFond(data[0].id);
          getATList(data[0].id);
        }
      });
    }
  }, [visible]);

  const getATList = (fondId: number) => {
    fetchATListByFondId(fondId).then((res) => {
      const { data: atData } = res;
      setATList(atData);
      if (atData.length > 0) {
        form.setFieldsValue({ archiveTypeId: atData[0].id });
      }
    });
  };

  const onFondChange = (val: number) => {
    getATList(val);
  };

  return (
    <>
      <Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入标题' }]}>
        <Input placeholder="请输入标题" />
      </Form.Item>
      <Form.Item label="全宗" rules={[{ required: true, message: '' }]}>
        <Select value={selectFond} onChange={onFondChange}>
          {fondList.map((fond) => (
            <Option key={fond.id} value={fond.id}>
              {fond.fondName}
            </Option>
          ))}
        </Select>
      </Form.Item>
      <Form.Item
        name="archiveTypeId"
        label="档案类型"
        rules={[{ required: true, message: '请选择档案类型' }]}
      >
        <Select>
          {aTList.map((at) => (
            <Option key={at.id} value={at.id}>
              {at.atName}
            </Option>
          ))}
        </Select>
      </Form.Item>
      <Form.Item
        name="applyTime"
        label="申请时间"
        rules={[{ required: true, message: '请选择申请时间' }]}
      >
        <JPDatePicker showTime />
      </Form.Item>
      <Form.Item name="description" label="申请描述">
        <Input.TextArea />
      </Form.Item>
    </>
  );
}

export default AuditFormItem;
